package cn.drenal.gui;

import cn.drenal.common.Constants;
import cn.drenal.common.Main;
import cn.drenal.helper.JDBCHelper;
import cn.drenal.pet.ItemPet;
import cn.drenal.pet.PetAnimal;
import cn.drenal.user.User;
import jdk.nashorn.internal.scripts.JO;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.event.*;
import java.util.ArrayList;

public class GuiUser extends PetGui
{
    private User usr;
    private JTable tablePurchase = new JTable();
    private JScrollPane panePurchaseTable = new JScrollPane();
    private JPanel paneBtn = new JPanel();
    private JPanel paneSelect = new JPanel();
    private JLabel labelTip = new JLabel("我想买");
    private JLabel labelBalance = new JLabel("账户余额：");
    private JButton btnLogout = new JButton("注销");
    private JButton btnExit = new JButton("退出");
    private JButton btnWithdraw = new JButton("充值");
    private JButton btnRecord = new JButton("清单");
    private JComboBox comboBoxType = new JComboBox();
    private ArrayList<PetAnimal> selectList = new ArrayList<>();
    private ArrayList<ItemPet> listPetPurchased = new ArrayList<>();

    public GuiUser(User usr)
    {
        this.usr = usr;
    }

    @Override
    public void showGui()
    {
        this.setSize(600, 420);
        this.setTitle("欢迎来到宠物商店");
        this.initComboBox();
        this.refreshItemTable(JDBCHelper.queryAllData());
        this.refreshLabelBalance();
        super.showGui();
    }

    @Override
    protected void addComp()
    {
        setLayout(null);
        //表格
        tablePurchase.getTableHeader().setReorderingAllowed(false);//列不能移动
        tablePurchase.getTableHeader().setResizingAllowed(false);//不可拉动表格
        tablePurchase.setEnabled(false);  //不可更改数据
        panePurchaseTable.setBounds(30, 30, 540, 300);
        panePurchaseTable.setViewportView(tablePurchase);
        //按钮层
        btnLogout.setBounds(0, 0, 40, 30);
        btnExit.setBounds(0, 0, 40, 30);
        btnWithdraw.setBounds(0, 0, 40, 30);
        btnRecord.setBounds(0, 0, 40, 30);
        paneBtn.add(btnLogout);
        paneBtn.add(btnExit);
        paneBtn.add(btnWithdraw);
        paneBtn.add(btnRecord);
        paneBtn.setBounds(0, 360, 600, 80);
        //筛选层
        labelTip.setBounds(0, 0, 30, 30);
        labelBalance.setBounds(0, 0, 30, 30);
        comboBoxType.setBounds(0, 0, 50, 30);
        //添加下拉菜单项
        ArrayList<String> dataList = JDBCHelper.selectPetAnimalType();
        comboBoxType.addItem("-请选择-");
        for (int i = 0; i < dataList.size(); i++)
        {
            comboBoxType.addItem(dataList.get(i));
        }
        paneSelect.add(labelTip);
        paneSelect.add(comboBoxType);
        paneSelect.add(labelBalance);
        paneSelect.setBounds(0, 330, 600, 30);
        //添加到GUIUser中
        this.add(paneBtn);
        this.add(paneSelect);
        this.add(panePurchaseTable);
    }

    @Override
    protected void addListener()
    {
        btnLogout.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                //关闭窗口
                dispose();
                //返回登录界面
                new GuiLogin().showGui();
                Main.consoleLog("用户" + usr.getUsrname() + "已注销。");
            }
        });
        btnExit.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                //关闭窗口
                dispose();
                //直接结束
                System.exit(0);
            }
        });
        btnWithdraw.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                JTextField money = new JTextField("5000");
                double mny;
                Object[] msg = {"请输入充值金额：", money};
                //屏蔽非法输入
                money.addKeyListener(new KeyAdapter()
                {
                    @Override
                    public void keyTyped(KeyEvent e)
                    {
                        int keyChar = e.getKeyChar();
                        if (!(keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9) && keyChar != '.')
                        {
                            e.consume(); //关键，屏蔽掉非法输入
                        }
                        else if (money.getText().contains("."))
                        {
                            //不能重复输入小数点
                            if (keyChar == '.')
                                e.consume();
                        }
                        else if (money.getText().equals("") && keyChar == '.')
                        {
                            e.consume();
                        }
                    }
                });
                int option = JOptionPane.showConfirmDialog(null, msg, "提示", JOptionPane.OK_CANCEL_OPTION);
                if (option == JOptionPane.OK_OPTION)
                {
                    try
                    {
                        mny = Double.parseDouble(money.getText());
                    }
                    catch (Exception exception)
                    {
                        JOptionPane.showMessageDialog(null, "请输入数据！", "提示", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                }
                else return;
                //充值
                JDBCHelper.withdraw(usr, mny);
                Main.consoleLog("充值完成。");
                refreshLabelBalance();
                initComboBox();
            }
        });
        btnRecord.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                //呼出购买清单窗口
                GuiList guiList = new GuiList("清单", listPetPurchased);
                guiList.showGui();
            }
        });
        comboBoxType.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                //每次选择选项都要刷新
                initComboBox();
            }
        });
        //购买
        tablePurchase.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                int foucusRowIndex = tablePurchase.rowAtPoint(e.getPoint());
                if (foucusRowIndex == -1) return;
                tablePurchase.setRowSelectionInterval(foucusRowIndex, foucusRowIndex);

                if (e.getButton() == MouseEvent.BUTTON3)//如果鼠标右键
                {
                    JPopupMenu tabMenu = new JPopupMenu();
                    JMenuItem purchase = new JMenuItem("购买");

                    purchase.addActionListener(new ActionListener()
                    {
                        @Override
                        public void actionPerformed(ActionEvent e)
                        {
                            int colCnt = tablePurchase.getColumnCount();
                            int rowInd = tablePurchase.getSelectedRow();
                            Object[] data = new String[colCnt];
                            //获得每列数据
                            for (int i = 0; i < colCnt; i++)
                            {
                                data[i] = tablePurchase.getValueAt(rowInd, i);
                            }
                            //弹出购买窗口
                            JTextField quantity = new JTextField("1");
                            int qtt;
                            Object[] msg = {"购买数量", quantity};
                            //屏蔽非法输入
                            quantity.addKeyListener(new KeyAdapter()
                            {
                                @Override
                                public void keyTyped(KeyEvent e)
                                {
                                    int keyChar = e.getKeyChar();
                                    if (!(keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9))
                                    {
                                        e.consume(); //关键，屏蔽掉非法输入
                                    }
                                }
                            });
                            int option = JOptionPane.showConfirmDialog(null, msg, "提示", JOptionPane.OK_CANCEL_OPTION);
                            if (option == JOptionPane.OK_OPTION)
                            {
                                //获得数量
                                try
                                {
                                    qtt = Integer.parseInt(quantity.getText());
                                }
                                catch (Exception exception)
                                {
                                    JOptionPane.showMessageDialog(null, "请输入数据！", "提示", JOptionPane.WARNING_MESSAGE);
                                    return;
                                }
                            }
                            else return;
                            PetAnimal thisPet = new PetAnimal((String) data[0], (String) data[1], (String) data[2], Double.parseDouble((String) data[3]), Integer.parseInt((String) data[4]));
                            //花钱
                            if (thisPet.getQuantity() - qtt < 0)//没货了
                            {
                                JOptionPane.showMessageDialog(null, "该宠物缺货中，暂不能购买此数量！", "提示", JOptionPane.INFORMATION_MESSAGE);
                                return;
                            }
                            if (thisPet.getPrice() * qtt > usr.getBalance())//没钱了
                            {
                                JOptionPane.showMessageDialog(null, "您没有足够的钱购买此商品！", "提示", JOptionPane.INFORMATION_MESSAGE);
                                return;
                            }
                            JDBCHelper.deposit(usr, thisPet, qtt);
                            //加入购买清单操作
                            boolean isExist = false;
                            //如果已经存在，就加入进清单
                            for (int i = 0; i < listPetPurchased.size(); i++)
                            {
                                if (listPetPurchased.get(i).getBreed().equals(thisPet.getBreed()))
                                {
                                    listPetPurchased.get(i).setQuantity(listPetPurchased.get(i).getQuantity() + qtt);
                                    isExist = true;
                                    break;
                                }
                            }
                            //如果不存在就加入清单
                            if (!isExist)
                            {
                                listPetPurchased.add(new ItemPet(thisPet.getBreed(), qtt, thisPet.getPrice()));
                            }
                            Main.consoleLog("用户" + usr.getUsrname() + "进行了购买操作");
                            refreshLabelBalance();
                            initComboBox();
                        }
                    });
                    tabMenu.add(purchase);
                    tabMenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });
    }

    //刷新表单
    public void refreshItemTable(ArrayList<PetAnimal> dataList)
    {
        //表头
        String[] tabHead = {Constants.NUM_TEXT, Constants.TYPE_TEXT, Constants.BREED_TEXT, Constants.PRICE_TEXT, Constants.QUANTITY_TEXT};
        //设置表单体
        String[][] tabBody = JDBCHelper.listToArray(dataList);
        TableModel model = new DefaultTableModel(tabBody, tabHead);
        tablePurchase.setModel(model);
    }

    //刷新下拉列表
    public void initComboBox()
    {
        if (comboBoxType.getSelectedIndex() != 0)
            refreshItemTable(JDBCHelper.selectPetAnimalWithType((String) comboBoxType.getSelectedItem()));
        else
            refreshItemTable(JDBCHelper.queryAllData());
    }

    //刷新余额标签
    public void refreshLabelBalance()
    {
        labelBalance.setText(usr.getUsrname() + "账户余额：" + usr.getBalance());
    }
}
